﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

namespace NEMProjectWebApp {
    /// <summary>
    /// Summary description for FileDownload
    /// </summary>
    public class FileDownload : IHttpHandler {

        public void ProcessRequest(HttpContext context) {
            Guid fileId = new Guid(context.Request.QueryString["FileId"]);

            using (SqlCommand command = new SqlCommand()) {
                // get the file from database
                command.Connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Asynchronous Processing=true");
                command.CommandText = "select * from Tananyag where Tan_ID = @FileId";
                command.Parameters.Add("@FileId", SqlDbType.UniqueIdentifier).Value = fileId;
                command.Connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader.Read()) {
                    // flush out the binary data to the user
                    context.Response.Clear();
                    context.Response.ContentType = (string)reader["Type"];
                    context.Response.AddHeader("Content-Disposition", String.Format("inline;filename={0};", reader["FileName"].ToString()));
                    context.Response.AddHeader("Content-Length", reader["FileSize"].ToString());
                    context.Response.BinaryWrite((byte[])reader["FileContent"]);
                    context.Response.End();
                }
            }
        }

        public bool IsReusable {
            get {
                return false;
            }
        }
    }
}